<template>
  <div class="filterField">
    <div class="filterField_header">
      <div class="filterField_title" style="margin-bottom: -8px;">筛选字段列表</div>
      <a-button type="primary" icon="plus" style="margin-top: 8px;" @click="onAddFilter">
        新建
      </a-button>
    </div>
    <!-- 表格 -->
    <a-table 
      :columns="columns" 
      :data-source="filterTable" 
      :pagination="false"
      rowKey="name"
      size="middle"
    >
      <span slot="action" slot-scope="row" v-if="row.name !== 'start' && row.name !== 'end'">
        <a @click="onUpdateFilter(row)">编辑</a>
        <a-divider type="vertical" />
        <a @click="onDeleteFilter(row)">删除</a>
      </span>
      <span slot="type" slot-scope="row"> 
        <div class="yuan_div">
          <span :class="row == 'select' ? 'yuan_dian' : 'lan_se'" style=""></span>{{row == 'input'? '输入' : '选择' }}
        </div>
      </span>
    </a-table>
    <a-modal v-model="visible" :title="title" @ok="handleOk" @cancel="hanleCancel" okText="确定" cancelText="取消" :maskClosable="false">
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <!-- 筛选字段 -->
        <a-form-model-item label="筛选字段" prop="name">
          <a-select placeholder="请选择" v-model="form.name" @select="onNameChange" show-search>
            <a-select-opt-group label="事件属性" v-show="filterForm.type==1 || filterForm.type == 2">
              <a-select-option v-for="item in eventProperties" :key="item.name" :value="item.name">
                {{ item.displayName }}
              </a-select-option>
            </a-select-opt-group>
            <a-select-opt-group label="用户属性">
              <a-select-option v-for="item in userProperties" :key="item.name" :value="item.name">
                {{ item.displayName }}
              </a-select-option>
            </a-select-opt-group>
            <a-select-opt-group label="用户分群">
              <a-select-option v-for="item in userGroups" :key="item.name" :value="item.name">
                {{ item.displayName }}
              </a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-model-item>
        <!-- 显示名 -->
        <a-form-model-item label="显示名" prop="displayName">
          <a-input v-model="form.displayName" placeholder="请输入显示名"/>
        </a-form-model-item>
        <!-- 类型 -->
        <a-form-model-item label="类型" prop="type">
          <a-select v-model="form.type" placeholder="请选择">
            <a-select-option value="select">
              选择
            </a-select-option>
            <a-select-option value="input">
              输入
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 可选项来源 -->
        <a-form-model-item v-if="form.type == 'select'" label="可选项来源" prop="optionType">
          <a-select v-model="form.optionType" placeholder="请选择">
            <a-select-option value="auto">
              行为分析平台
            </a-select-option>
            <a-select-option value="sql" v-if="typeIsSql">
              sql
            </a-select-option>
            <a-select-option value="dict">
              字典
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 字典列表 -->
        <a-form-model-item 
          v-if="form.type == 'select' && ['dict', '字典'].includes(form.optionType) || form.type == 'select' && form.optionType =='sql' " 
          :label="form.optionType == 'sql' ? 'sql查询' :'字典列表'" 
          prop="options"
        >
          <a-input v-if="['dict', '字典'].includes(form.optionType)" v-model="form.options" type="textarea" placeholder="请输入" />
          <a-input v-if="form.optionType =='sql'" v-model="form.options" type="textarea" placeholder="请输入sql语句" />
          <a-alert v-if="['dict', '字典'].includes(form.optionType)" message="字典项格式为'key,value'，字典项之间以换行分隔。" type="info" />
          <a-alert v-if="form.optionType =='sql'" message="sql语句的返回结果必须包含value和displayName两列，其中value对应可选项的值，displayName对应可选项的显示名。" type="info" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
  const columns = [
    { 
      title: '字段名', 
      dataIndex: 'name', 
      align: 'center'
    },
    { 
      title: '字段显示名', 
      dataIndex: 'displayName', 
      align: 'center'
    },
    { 
      title: '类型', 
      dataIndex: 'type', 
      align: 'center',
      scopedSlots: { customRender: 'type' },
    },
    { 
      title: '可选项来源', 
      dataIndex: 'optionType',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      scopedSlots: { customRender: 'action' },
    }
  ]
  export default {
    data() {
      return {
        columns,
        visible: false,
        title: '新建筛选字段',
        form :{
          name: '',
          displayName: '',
          type: ''
        },
        rules: {
            name: [ 
              { required: true, message: '请选择字段名', trigger: 'change' },
            ],
            displayName: [ 
              { required: true, message: '请输入显示名', trigger: 'blur' },
              { max: 100, message: '最大长度为100个字符', trigger: 'blur' }
            ],
            type: [
              { required: true, message: '请选择类型', trigger: 'change' }
            ]
        },
        filterList: [],
        oldForm: {}
      }
    },
    props: ['filterForm'],
    watch: {
      filterList: {
        handler (val) {
          this.filterForm.filter = JSON.parse(JSON.stringify(val))
        },
        deep: true
      },
      visible (val) {
        if (!val) {
          this.form = {};
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate();
        }
      }
    },
    computed: {
      ...mapState('custom', ['reportForm', 'datasource_list']),
      ...mapState('analyseType', ['propertiesEvent', 'propertiesUser']),
      typeIsSql () {
        let isDis = false
        this.datasource_list.forEach(data =>{
          if(data.id == this.filterForm.datasourceId) {
            if (data.type == 1) {
              isDis = true
            }
          }
        })
        return isDis
      },
      filterTable () {
        return this.filterList.map(item => {
          let type = ''
          if (item.optionType == 'auto') {
            type = '行为分析平台'
          } else if (item.optionType == 'sql') {
            type = 'sql'
          } else if (item.optionType == 'dict') {
            type = '字典'
          } else {
            type = '无'
          }
          return {...item, optionType: type }
        })
      },
      properties () {
        return [...this.propertiesEvent,...this.propertiesUser]
      },
      eventProperties: function () {
        return this.properties.filter((item) => {
            return item.name.indexOf("events.") === 0 || item.name.indexOf("virtual.events.") === 0
        });
      },
      userProperties: function () {
        return this.properties.filter((item) => {
            return (item.name.indexOf("users.") === 0 || item.name.indexOf("virtual.users.") === 0) && item.name.indexOf("users.cg_") !== 0
        });
      },
      userGroups: function () {
        return this.properties.filter((item) => {
            return item.name.indexOf("users.cg_") === 0
        });
      },
    },
    methods: {
      onUpdateFilter (row) {
        this.title = '编辑筛选字段'
        this.visible = true
        this.form = { ...row }
        this.oldForm = {...row }
      },
      onDeleteFilter (row) {
        this.$confirm({
          title: '提示',
          content: '确定要删除吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            let index = null
            this.filterList.forEach((item,idx) => {
              if(item.name == row.name && item.displayName == row.displayName) {
                index = idx
              }
            })
            this.filterList.splice(index, 1)
          },
          onCancel: () => {},
        })
      },
      onAddFilter () {
        this.title = '新建筛选字段'
        this.visible = true
      },
      onNameChange (val) {
        this.form = {
          name: val,
          displayName: '',
          type: ''
        }
        for (let i=0; i<this.properties.length; i++){
          if (this.properties[i].name == this.form.name) {
            this.form.displayName = JSON.parse(JSON.stringify(this.properties[i].displayName))
          }
        }
      },
      hanleCancel () {},
      handleOk () {
        if (this.form.type == 'input') {
          this.form.optionType = '无'
          this.form.options = '无'
        }
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.visible = false
            if (this.title == '新建筛选字段') {
              this.filterList.push(JSON.parse(JSON.stringify(this.form)))
            } else {
              this.filterList.forEach((v, i) => {
                v.name == this.oldForm.name && this.filterList.splice(i, 1, JSON.parse(JSON.stringify(this.form)))
              })
            }
            this.form = {}
          } else {
            return false;
          }
        });
      },
      setTable () {
          this.filterList.push({
            name: 'start',
            displayName: '开始日期',
            type: 'input',
            optionType: '无'
          })
          this.filterList.push({
            name: 'end',
            displayName: '结束日期',
            type: 'input',
            optionType: '无'
          })
      },
      initTable () {
        let filter = []
        filter = [...JSON.parse(JSON.stringify(this.filterForm.filter))]
        this.filterList = filter
      },
    },
    mounted() {
      if (this.filterForm.filter.length) {
        this.initTable()
      }else{
        this.setTable()
      }
    },
  }
</script>

<style scoped>
.filterField>.ant-table-wrapper>>>.ant-spin-nested-loading {
  margin-top: 24px;
}

.yuan_dian {
  width: 5px;
  height: 5px; 
  display: inline-block; 
  background-color: #ccc;
  border-radius: 50%;
  margin-right: 4px;
}

.lan_se {
  width: 5px;
  height: 5px; 
  display: inline-block; 
  border-radius: 50%;
  margin-right: 4px;
  background-color: #1890ff;
}

.yuan_div {
  display: flex;
  justify-content: center;
  align-items: center;
}

.filterField .filterField_title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0,0,0,.85);
}

.filterField_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>